<?php
/*
* @version 2010-11-03
* @author mxrgus.pxrt
*
*
* 1. Call comes in JSON packed in base64
* 2. Its extracted to array
* 3. Data is passed to proxy, proxy takes care off logging etc auth
* 4. Data is passed to Supportworks
* 5. Data is passsed back to caller (echoed) in base64 containing JSON of 
* 
*/


// Conf
include_once('config/_init.php');

// Helper functions
include_once('classes/helpers/object_to_array.php');

// Classes
include_once('classes/Logger.php');
include_once('classes/Object.php');
include_once('classes/Supportworks.php');
include_once('classes/Proxy.php');


# Test
#
# $_REQUEST['data'] = base64_encode(json_encode(array('command'=>'UPDATE CALL VALUES ', 'args'=>array('callref'=>'16950', 'c_rating'=>'5', 'c_ratingtxt'=>'test'))));



function main(){

    // Data is packet into base64 in json format
    $data_b64       = $_REQUEST['data'];
    $data_json      = base64_decode($data_b64);
    $data_ob        = json_decode($data_json);
    $data           = object_to_array($data_ob, true);

    Logger::info(array($_SERVER['REMOTE_ADDR'].' Input Data' => array($data) ));
    Logger::debug(array($_SERVER['REMOTE_ADDR'].' Input Data' => array($data_b64, $data_json, $data_ob, $data) ));


    // Call is forwarded to proxy, proxy forwards it to supportworks.
    $proxy          = new Proxy();
    $response_ob    = $proxy->forward($data['command'], $data['args']);

    // Data returned from proxy is converted back to json -> base64 and returned
    $response       = object_to_array($response_ob, true);
    $response_json  = json_encode($response);
    $response_b64   = base64_encode($response_json);

    Logger::info(array($_SERVER['REMOTE_ADDR'].' Output Data' => array($response) ));
    Logger::debug(array($_SERVER['REMOTE_ADDR'].' Output Data' => array($response_b64, $response_json, $response_ob) ));


    echo $response_b64;

}


main();
